<template>
  <div class="container">
    <!-- 头部 -->
    <Banner
      :connected="state.connected"
      :batteryLeval="state.batteryLeval"
      :lowBatteryNotify="state.lowBatteryNotify"
      :useSize="state.useSize"
    />

    <!-- mode -->
    <div>
      <div
        :class="[
          state.curDisabledList.includes(state.disabledList[0]) ? 'mask' : ''
        ]"
      ></div>
      <!-- 模式 -->
      <Mode
        :workTime="state.workTime"
        :mode="state.mode"
        :useSize="state.useSize"
        :strength="state.strength"
        @emitModeChange="onEmitModeChange"
      />
    </div>

    <AD />
    <!-- 历史记录 -->
    <div>
      <div
        :class="[
          state.curDisabledList.includes(state.disabledList[1]) ? 'mask' : ''
        ]"
      ></div>
      <history-record
        :list="
          state.record.length > 4 ? state.record.slice(0, 4) : state.record
        "
        :week="state.week"
      />
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted, ref, watch, nextTick } from 'vue'
import { useStore } from 'vuex'

import { deviceId } from '@/utils/enum'
const { convertDuration, convertTime, contrastDay } = require('@/utils/util')
import EventBus from '@/assets/common/EventBus'

import AD from './AD.vue'
import Banner from './Banner.vue'
import Mode from './Mode.vue'
import HistoryRecord from '@/components/HistoryRecord/Index.vue'
import { useRoute } from 'vue-router'
import { showDialog } from 'vant'

const route = useRoute()
const store = useStore()
let state = reactive({
  disabledList: [1, 2], // 1=模式 2=历史记录
  curDisabledList: [],

  connected: true, // 设备是否离线
  batteryLeval: 100, // 电池电量
  workTime: 2, // 刷牙时间
  mode: 0, // 模式
  strength: 0, // 工作强度
  useSize: 180, // 刷头次数
  lowBatteryNotify: 0, // 低电量通知 0-正常 1-低电量
  brushRecord: '', // 刷牙记录

  timer: undefined,
  record: [],
  todayTime: null,
  week: ''
})

const gDeviceInfo = ref({})

watch(
  () => route.query,
  (to, from) => {
    // 在这里处理路由变化的逻辑

    if (to.random || to.offline) {
      // 处理路由变化-离开页面
    } else {
      // 处理路由变化-进入页面

      nextTick(() => {
        if (window.WebViewJavascriptBridge) {
          window.WebViewJavascriptBridge.callHandler(
            'setToolbarTitle',
            'usmile声波电动牙刷 P8 CMCC',
            null
          )
        } else {
          console.error('window.WebViewJavascriptBridge 未定义')
        }
      })
    }
  },
  {
    // immediate: true,
    deep: true
  }
)

watch(
  () => state.useSize,
  val => {
    if (val <= 14) {
      lowUsesize()
    }
  },
  {
    immediate: true,
    deep: true
  }
)

EventBus.on('startInterval', () => {
  intervalEvent()
})
EventBus.on('stopInterval', () => {
  clearInterval(state.timer)
})

onMounted(() => {
  getweek()
  Hejia.ready(function () {
    if (window.WebViewJavascriptBridge) {
      window.WebViewJavascriptBridge.callHandler(
        'setToolbarTitle',
        'usmile声波电动牙刷 P8 CMCC',
        null
      )
    }

    // 页面加载完成后要立即调用Hejia全局对象执行的代码逻辑写这里
    state.todayTime = getToday()
    getDeviceInfo()
    intervalEvent()
    getHistoryParam()
  })
})

const lowUsesize = () => {
  showDialog({
    confirmButtonText: '确定',
    message: '您的刷头使用次数不足，易滋生细菌，专业牙医建议您及时更换并重置！'
  }).then(() => {
    // on close
  })
}

const getToday = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth()
  const day = date.getDate()
  return new Date(year, month, day).getTime()
}

const getweek = () => {
  const date = new Date()
  const dayOfWeek = date.getDay()
  const chineseDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  state.week = chineseDays[dayOfWeek]
}

// 获取刷牙的历史记录
const getHistoryParam = params => {
  Hejia.getHistoryParam(
    {
      // deviceId,
      paramName: ['brushRecord'],
      startDate: state.todayTime,
      endDate: state.todayTime + 86400000
    },
    function (arr) {
      if (arr.length) {
        state.record = arr.filter((item, index, self) => {
          const itemVal = item.params[0].value
          return (
            index ===
            self.findIndex(obj => {
              const arrVal = obj.params[0].value
              return itemVal === arrVal
            })
          )
        })
        // 去重操作，上报数据有重复的
        state.record = state.record.filter(item => {
          const { value } = item.params[0]
          const time = parseInt(value.substring(0, 8), 16)

          if (contrastDay(time, new Date().getDate())) {
            return item
          }
        })

        // 排序
        state.record = state.record.sort((a, b) => {
          const aData = parseInt(a.params[0].value.substring(0, 8), 16)
          const bData = parseInt(b.params[0].value.substring(0, 8), 16)

          return bData - aData
        })

        // 筛选出有效刷牙时长 >=30s
        state.record = state.record.filter(item => {
          const { value } = item.params[0]
          const duration = parseInt(value.substring(10, 14), 16)
          if (duration >= 30) {
            return item
          }
        })

        // 有乱序问题，根据上报数据的时间戳排序展示
        state.record = state.record.map(item => {
          const { value } = item.params[0]
          const time = parseInt(value.substring(0, 8), 16)
          const score = parseInt(value.substring(8, 10), 16)
          const duration = parseInt(value.substring(10, 14), 16)

          return {
            time: convertTime(time),
            score,
            duration: convertDuration(duration),
            id: Math.random()
          }
        })
      } else {
        state.record = []
      }
    },
    function (msg, obj) {
      console.log(obj.resultCode + obj.resultCodeMessage)
    }
  )
}

const intervalEvent = () => {
  clearInterval(state.timer)
  state.timer = setInterval(() => {
    getDeviceInfo()
    getHistoryParam()
  }, 1000 * 1)
}

// 设备信息-轮询
// deviceId
const getDeviceInfo = () => {
  Hejia.getDeviceInfo(
    {},
    function (obj) {
      state.deviceInfo = obj.device.parameters
      store.commit('setInfo', state.deviceInfo)
      store.commit('setConnected', obj.device.connected)

      // 设备是否在线
      // state.connected = obj.device.connected
      state.connected = true
      if (state.connected) {
        state.connected = true
        state.curDisabledList = []
      } else {
        // 离线，此处只处理离线状态，其他状态在parseData中处理
        // state.connected = false
        state.curDisabledList = [1, 2]
        // return
      }

      parseData(state.deviceInfo)
    },
    function (msg, obj) {
      console.log(obj.resultCode + obj.resultCodeMessage)
    }
  )
}

const parseData = params => {
  params.forEach(e => {
    let value = Number(e.value)

    const keys = [
      'batteryLeval',
      'workTime',
      'mode',
      'strength',
      'useSize',
      'lowBatteryNotify',
      'brushRecord'
    ]
    if (keys.includes(e.name)) {
      if (e.name == 'brushRecord') {
        state[e.name] = e.value
      } else {
        state[e.name] = Number(e.value)
      }
      const {
        batteryLeval,
        workTime,
        mode,
        strength,
        useSize,
        lowBatteryNotify,
        brushRecord
      } = state
      // 获取对象的ref引用 xx.value
      gDeviceInfo.value = {
        batteryLeval,
        workTime,
        mode,
        strength,
        useSize,
        lowBatteryNotify,
        brushRecord
      }

      store.commit('setDeviceInfo', gDeviceInfo.value)
    }
  })
}

const onEmitModeChange = (mode, strength) => {
  state.mode = mode
  state.strength = strength
}
</script>

<style lang="less" scoped>
@import url(../../assets/style/style.less);
.history-record {
  margin: 0 32px;
  & > .body {
    padding-left: 0 !important;
  }
}
</style>
